package com.cloud.xtools.user.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.xtools.common.exception.ServiceException;
import com.cloud.xtools.common.response.PageList;
import com.cloud.xtools.common.util.Dump;
import com.cloud.xtools.common.util.XPage;
import com.cloud.xtools.user.domain.entity.Permission;
import com.cloud.xtools.user.domain.query.admin.PermissionQuery;
import com.cloud.xtools.user.domain.request.admin.PermissionCreateRequest;
import com.cloud.xtools.user.domain.request.admin.PermissionUpdateRequest;
import com.cloud.xtools.user.domain.resource.admin.PermissionResource;
import com.cloud.xtools.user.domain.resource.admin.PermissionTreeResource;
import com.cloud.xtools.user.mapper.PermissionMapper;
import com.cloud.xtools.user.service.admin.PermissionService;
import com.cloud.xtools.user.service.admin.RolePermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Daixinguo
 */
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private final PermissionMapper permissionMapper;

    private final RolePermissionService rolePermissionService;

    @Override
    public Long countByIds(List<Long> permissionIds) {
        QueryWrapper<Permission> queryWrapper = Wrappers.query();
        queryWrapper.in("id", permissionIds);
        return count(queryWrapper);
    }

    @Override
    public PageList list(PermissionQuery permissionQuery) {
        QueryWrapper<Permission> queryWrapper = Wrappers.query();
        if (permissionQuery.getParentId() == null) {
            queryWrapper.isNull("parent_id");
        } else {
            queryWrapper.eq("parent_id", permissionQuery.getParentId());
        }

        // IPage<Permission> page = new Page<>(permissionQuery.getPageNumber(), permissionQuery.getPageSize());
        // IPage<Permission> permissionList = permissionMapper.selectPage(page, queryWrapper);
        // System.out.println(permissionList);

        XPage.startPage(permissionQuery.getPageNum(), permissionQuery.getPageSize());
        List<Permission> permissions = permissionMapper.selectList(queryWrapper);
        return XPage.page(permissions, PermissionResource.class);
    }

    // 所有数据（不分页）
    @Override
    public List<PermissionTreeResource> treeList(){
        List<Permission> permissionList = list();
        List<PermissionTreeResource> permissionTreeResources = BeanUtil.copyToList(permissionList, PermissionTreeResource.class);
        // 打印成格式化后的 json
        // Dump.json(buildTree(permissionTreeResources));
        return buildTree(permissionTreeResources);
    }

    @Override
    public PermissionResource add(PermissionCreateRequest permissionCreateRequest) {
        Permission permission = BeanUtil.copyProperties(permissionCreateRequest, Permission.class);
        save(permission);
        return BeanUtil.copyProperties(permission, PermissionResource.class);
    }

    @Override
    public void edit(Long id, PermissionUpdateRequest permissionUpdateRequest) {
        permissionUpdateRequest.setId(id);
        Permission permission = BeanUtil.copyProperties(permissionUpdateRequest, Permission.class);
        try {
            updateById(permission);
        } catch (Exception e) {
            throw new ServiceException("更新失败");
        }
    }

    @Override
    public void destroy(Long id) {
        try {
            rolePermissionService.destroyByPermissionId(id);
            removeById(id);
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }

    // 根据 id 查询 identity
    @Override
    public List<String> getIdentityByIds(List<Long> permissionIds) {
        QueryWrapper<Permission> queryWrapper = Wrappers.query();
        queryWrapper.select("identity");
        queryWrapper.in("id", permissionIds);
        List<Permission> permissions = permissionMapper.selectList(queryWrapper);
        List<String> identities = new ArrayList<>();
        for (Permission permission : permissions) {
            identities.add(permission.getIdentity());
        }
        return identities;
    }

    public List<PermissionTreeResource> buildTree(List<PermissionTreeResource> permissions) {
        Map<Long, PermissionTreeResource> map = new HashMap<>();
        List<PermissionTreeResource> rootList = new ArrayList<>();

        // 将所有节点放入map中，key为id，value为节点对象
        for (PermissionTreeResource permission : permissions) {
            map.put(permission.getId(), permission);
        }

        // 遍历所有节点，根据parentId构建树形结构
        for (PermissionTreeResource permission : permissions) {
            if (permission.getParentId() == null) {
                rootList.add(permission);
            } else {
                PermissionTreeResource parent = map.get(permission.getParentId());
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(permission);
            }
        }

        return rootList;
    }
}
